import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../gsp_converter_util.dart';
import 'package:flutter_map/plugin_api.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong/latlong.dart';
import 'package:leaflet_geo_fence_app/plugin/userlocation/user_location_options.dart';

///@className user_location_layer
///@author liaoyu
///@version 1.0.0
///@description 用户位置
///@createTime 2021/1/12 14:41
class UserLocationLayer extends StatefulWidget {
  final UserLocationOptions options;
  final MapState mapState;
  final Stream<Null> stream;

  const UserLocationLayer({Key key, this.options, this.mapState, this.stream}) : super(key: key);

  @override
  _UserLocationLayerState createState() => _UserLocationLayerState();
}

class _UserLocationLayerState extends State<UserLocationLayer> {
  final translateUrl = 'http://api.map.sogou.com/engine/api/translate/json';
  ValueNotifier<LatLng> _vnLocation;
  final _markerSize = 40.0;

  @override
  void initState() {
    _vnLocation = ValueNotifier(LatLng(0.0, 0.0));
    print("_UserLocationLayerState initState");
    _getLocation();
    super.initState();
  }

  @override
  void dispose() {
    _vnLocation.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints bc) {
        final size = Size(bc.maxWidth, bc.maxHeight);
        return _build(context, size);
      },
    );
  }

  Widget _build(BuildContext context, Size size) {
    return StreamBuilder<void>(
      stream: widget.stream, // a Stream<void> or null
      builder: (BuildContext context, _) {
        return ValueListenableBuilder(
            valueListenable: _vnLocation,
            builder: (BuildContext context, LatLng value, Widget child) {
              Marker _marker = Marker(
                point: value,
                width: _markerSize,
                height: _markerSize,
                builder: (ctx) => Container(
                  width: _markerSize,
                  height: _markerSize,
                  color: Colors.green,
                  child: Icon(
                    Icons.local_airport,
                    color: Colors.blue,
                  ),
                ),
              );
              var pos = widget.mapState.project(value);
              pos = pos.multiplyBy(widget.mapState.getZoomScale(widget.mapState.zoom, widget.mapState.zoom)) -
                  widget.mapState.getPixelOrigin();

              var pixelPosX =
              (pos.x - (_marker.width - _marker.anchor.left)).toDouble();
              var pixelPosY =
              (pos.y - (_marker.height - _marker.anchor.top)).toDouble();

              var bottomPos = widget.mapState.pixelBounds.max;
              bottomPos =
                  bottomPos.multiplyBy(widget.mapState.getZoomScale(widget.mapState.zoom, widget.mapState.zoom)) -
                      widget.mapState.getPixelOrigin();

              return Container(
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      width: _marker.width,
                      height: _marker.height,
                      left: pixelPosX,
                      top: pixelPosY,
                      child: _marker.builder(context),
                    )
                  ],
                ),
              );
            });
      },
    );
  }

  Future<void> _getLocation() async {
    try {
      final Position _position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
      print("_getLocation _position:${_position}");
      if(_position != null){

//        Map<String,String> data = {'points':'${_position.longitude.toString()},${_position.latitude.toString()}','type':'1'};
//        Response response = await Dio().request(translateUrl,
//          queryParameters: data,
//          options: Options(method: 'get', contentType: Headers.formUrlEncodedContentType),
//        );
        LatLng latLng = GpsConverterUtil.gps84_To_Gcj02(_position.latitude, _position.longitude);
        if(latLng != null){
          _vnLocation.value = latLng;
          if(widget.options.latlongChange != null){
            widget.options.latlongChange(latLng);
          }
        }
      }

    } catch (err) {
      print("_getLocation err:${err}");
    }
  }
//  String _template(Map<String, String> data) {
//    return translateUrl.replaceAllMapped(_templateRe, (Match match) {
//      var value = data[match.group(1)];
//      if (value == null) {
//        throw Exception('No value provided for variable ${match.group(1)}');
//      } else {
//        return value;
//      }
//    });
//  }
}
